﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    public partial class AddRole : Form
    {

        /// <summary>
        /// 角色ID
        /// </summary>
        public static int RoleId { get; set; }

        /// <summary>
        /// 角色名称
        /// </summary>
        public static string RoleName { get; set; }

        /// <summary>
        /// 角色是否启用
        /// </summary>
        public static bool RoleState { get; set; }

        public AddRole()
        {
            InitializeComponent();

        }

        private void AddRole_Load(object sender, EventArgs e)
        {
            string sql = string.Format(@"select id,MenuNo,MenuName,IFNULL(Parentid,0) as Parentid ,
                            IFNULL((select 1 from roleinmenu where roleID = {0} and menuID = systemmenu.id),0) as 'IsChecked' 
                            from systemmenu  where MenuState = 1", RoleId);

            //查询出所有的菜单
            var menuList = UserOpMysql.ExecuteDataTable(sql);
            if (menuList.Rows.Count > 0)
            {
                //把DataTable转换为集合
                List<SystemMenu> systemMenus = menuList.ConvertToListClass<SystemMenu>();

                //调用封装的菜单加载方法
                PageDataDto.BuildThreeLevelMenu(TrvRole, systemMenus);
            }

            //roleID 不为0 时意为修改
            if (RoleId > 0)
            {
                TbxName.Text = RoleName;

                //设置启用状态
                CkbStatus.Checked = RoleState;

            }

        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            RoleName = this.TbxName.Text; //角色名称
            RoleState = this.CkbStatus.Checked;//是否启用

            List<int> ids = new List<int>();
            List<string> names = new List<string>();



            // 处理每个节点
            foreach (TreeNode node in TrvRole.Nodes[0].Nodes)
            {
                if (node.Checked)
                {
                    var data = ((SystemMenu)node.Tag);
                    ids.Add(data.Id);
                    names.Add(data.MenuName);
                }

                foreach (TreeNode childNode in node.Nodes)
                {
                    // 处理每个子节点
                    if (childNode.Checked)
                    {
                        var data = ((SystemMenu)childNode.Tag);
                        ids.Add(data.Id);
                        names.Add(data.MenuName);
                    }


                    foreach (TreeNode thirdLevelMenu in childNode.Nodes)
                    {
                        // 处理每个子节点
                        if (thirdLevelMenu.Checked)
                        {
                            var data = ((SystemMenu)thirdLevelMenu.Tag);
                            ids.Add(data.Id);
                            names.Add(data.MenuName);
                        }

                    }
                }
            }

            //所有选中的ID
            string selectedMenuIds = String.Join(",", ids);
            string rolePermissions = String.Join("/", names);



            if (string.IsNullOrWhiteSpace(RoleName))
            {
                MessageBox.Show("角色名称不能为空！", "参数有误！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (ids.Count == 0)
            {
                MessageBox.Show("角色菜单不能为空！", "参数有误！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            //存储过程名称
            string sql = "InsertAndUpdateRoleAndMenus";

            List<MySqlParameter> mySqlParameters = new List<MySqlParameter>()
            {
                new MySqlParameter("?p_roleName",MySqlDbType.VarChar){Value=RoleName},
                new MySqlParameter("?p_rolePermissions",MySqlDbType.Text){Value=rolePermissions},
                new MySqlParameter("?p_state",MySqlDbType.Int32){Value=RoleState},
                new MySqlParameter("?p_selectedMenuIds",MySqlDbType.VarChar){Value=selectedMenuIds},
                new MySqlParameter("?p_opid",MySqlDbType.Int32){Value=RoleId}

            };

            var result = UserOpMysql.ExecuteStoredProcedureToDataTable(sql, mySqlParameters);
            if (result.Rows.Count > 0)
            {
                MessageBox.Show(result.Rows[0]["message"].ToString(), "处理信息！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {

            this.Close();

        }

        private void TbxName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar))//输入1-8位数字或字母
            {
                if (TbxName.Text.Length <= 7)
                {
                    e.Handled = false;
                }
                else if (TbxName.SelectionLength > 1)
                {
                    e.Handled = false;//选择多个
                }
                else
                {
                    e.Handled = true;
                }
            }

            //e.KeyChar == '.' ||
            else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                e.Handled = false;//删除
            else
                e.Handled = true;
        }
    }
}
